<template>
    <div>
        <el-dialog v-model="props.isShow" :title="props.isAdd ? '添加列表' : '编辑列表'" center :before-close="beforeClose">
            <el-form :model="bannerForm" :rules="rules" ref="bannerRef">
                <el-form-item label="标题" :label-width="formLabelWidth" prop="title">
                    <el-input v-model="bannerForm.title" autocomplete="off" />
                </el-form-item>
                <el-form-item label="图片" :label-width="formLabelWidth">
                    <el-upload v-model:file-list="fileList" action="#" list-type="picture-card" :on-preview="onPreview"
                        :on-remove="handleRemove" :on-change="onChange" :limit="1">
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </el-upload>
                    <el-dialog v-model="dialogVisible">
                        <img w-full :src="dialogImageUrl" alt="Preview Image" />
                    </el-dialog>
                </el-form-item>
                <el-form-item label="状态" :label-width="formLabelWidth">
                    <el-switch v-model="bannerForm.status"
                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" :active-value="1"
                        :inactive-value="2" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cancel(bannerRef)">取消</el-button>
                    <el-button type="primary" @click="sure(bannerRef)">添加</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script lang='ts' setup>
import { defineProps, ref, reactive } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import type { UploadProps, UploadUserFile, FormRules, FormInstance } from 'element-plus'
import { bannerAdd, bannerEdit, bannerInfo } from '../../request/api'
import { useStore } from 'vuex'
let store = useStore()

//id的值先为0
var newId = 0

let props = defineProps({
    isShow: Boolean,
    isAdd: Boolean
})

let bannerForm = ref<any>({
    title: '',//轮播图名称
    img: '',//图片(文件)
    status: 1,//状态  1正常2禁用
})

//子传父
let emit = defineEmits(['cancel'])

// //封装一个取消事件
// const cancel = (formEl?: FormInstance | undefined) => {
//     if (!formEl) return
//     bannerForm.value = {
//         title: '',//轮播图名称
//         img: '',//图片(文件)
//         status: 1,//状态  1正常2禁用
//     }
//     //清除表单验证
//     formEl.resetFields()
//     fileList = []
// }

//关闭x事件
const beforeClose = (done: any) => {
    done()
    cancel(bannerRef.value)
}
//封装一个取消事件
const cancel = (formEl?: FormInstance | undefined) => {
    emit('cancel', false)
    if (!formEl) return
    bannerForm.value = {
        title: '',//轮播图名称
        img: '',//图片(文件)
        status: 1,//状态  1正常2禁用
    }
    //清除表单验证
    formEl.resetFields()
    fileList = []
}

const bannerRef = ref<FormInstance>()

let fileList: { url: string }[] = []
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
}
const onChange: UploadProps['onChange'] = (uploadFile) => {
    bannerForm.value.img = uploadFile.raw
}

const onPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}

const formLabelWidth = '140px'

const rules = reactive<FormRules>({
    title: [
        { required: true, message: '请填写轮播图名称', trigger: 'blur' },
        { min: 2, max: 8, message: '长度字符为2-8', trigger: 'blur' },
    ]
})

// const add = async (formEl?: FormInstance | undefined) => {
//     if (!formEl) return
//     await formEl.validate(val => {
//         if (val) {
//             if (props.isAdd) {
//                 bannerAdd(bannerForm.value).then(res => {
//                     if (res.code == 200) {
//                         console.log(res);
//                         ElMessage({
//                             message: res.msg,
//                             type: 'success',
//                         })
//                         store.dispatch('banner/getBannerListAction')
//                         cancel(formEl)
//                     } else {
//                         ElMessage.error(res.msg)
//                     }
//                 })
//             } else {
//                 bannerEdit({ ...bannerForm.value, id: newId }).then(res => {
//                     if (res.code == 200) {
//                         ElMessage({
//                             message: res.msg,
//                             type: 'success',
//                         })
//                         store.dispatch('banner/getBannerListAction')
//                         cancel(formEl)
//                     } else {
//                         ElMessage.error(res.msg)
//                     }
//                 })
//             }
//         }
//     })
// }

const sure = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((val) => {
        if (val) {
            if (props.isAdd) {
                bannerAdd(bannerForm.value).then(res => {
                    if (res.code == 200) {
                        console.log(res);
                        ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                        store.dispatch('banner/getBannerListAction')
                        cancel(formEl)
                    } else {
                        ElMessage.error(res.msg)
                    }
                })
            } else {
                bannerEdit({ ...bannerForm.value, id: newId }).then(res => {
                    if (res.code == 200) {
                        ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                        store.dispatch('banner/getBannerListAction')
                        cancel(formEl)
                    } else {
                        ElMessage.error(res.msg)
                    }
                })
            }
        }
    })
}

//封装一个数据回显
const lookup = (id: number) => {
    bannerInfo({ id }).then((res: any) => {
        // console.log(id);    
        bannerForm.value = res.list
        // menuForm.value.id = id
        // console.log(res);
        newId = id
        //图片回显
        fileList = bannerForm.value.img ? [{ url: bannerForm.value.img }] : []
    })
}

defineExpose({
    lookup
})
</script>
<style lang='less' scoped></style>